import { User } from '../models/User.js';
import { UserRole } from '../models/UserRole.js';
import { RolePermission } from '../models/RolePermission.js';
import { Permission } from '../models/Permission.js';
import { Teacher } from '../models/Teacher.js';

const userModel = new User();
const userRoleModel = new UserRole();
const rolePermissionModel = new RolePermission();
const permissionModel = new Permission();
const teacherModel = new Teacher();

// 获取用户角色
async function getUserRoles(userId) {
    const userRoles = userRoleModel.findAll().filter(ur => ur.userId === userId);
    return userRoles.map(ur => ur.roleId);
}

// 检查用户是否有指定权限
async function hasPermission(userId, permissionCode) {
    try {
        // 获取用户的所有角色
        const roleIds = await getUserRoles(userId);
        console.log(`[权限检查] 用户 ${userId} 的角色ID:`, roleIds);

        // 如果是管理员角色（roleId: 1），拥有所有权限
        if (roleIds.includes(1)) {
            console.log(`[权限检查] 用户 ${userId} 是管理员，拥有所有权限`);
            return true;
        }

        // 获取权限ID
        const permission = permissionModel.findOne({ code: permissionCode });
        if (!permission) {
            console.log(`[权限检查] 权限 ${permissionCode} 不存在`);
            return false;
        }
        console.log(`[权限检查] 权限 ${permissionCode} 的ID:`, permission.id);

        // 检查是否有该权限
        const rolePermissions = rolePermissionModel.findAll();
        const hasAccess = rolePermissions.some(rp => {
            const matches = roleIds.includes(rp.roleId) && rp.permissionId === permission.id;
            if (matches) {
                console.log(`[权限检查] 找到匹配权限: roleId=${rp.roleId}, permissionId=${rp.permissionId}`);
            }
            return matches;
        });

        console.log(`[权限检查] 用户 ${userId} 对权限 ${permissionCode} 的检查结果:`, hasAccess);
        return hasAccess;
    } catch (error) {
        console.error('[权限检查] 检查权限失败:', error);
        return false;
    }
}

// 检查用户是否是管理员
async function isAdmin(userId) {
    const roleIds = await getUserRoles(userId);
    return roleIds.includes(1); // admin roleId = 1
}

// 检查用户是否是教师
async function isTeacher(userId) {
    const roleIds = await getUserRoles(userId);
    return roleIds.includes(2); // teacher roleId = 2
}

// 检查是否可以编辑/删除特定教师
async function canManageTeacher(userId, teacherId) {
    // 管理员可以管理所有教师
    if (await isAdmin(userId)) {
        return true;
    }

    // 教师只能管理自己（通过phone匹配）
    const user = userModel.findOne({ id: userId });
    if (!user || !user.phone) {
        return false;
    }

    const teacher = teacherModel.findOne({ id: teacherId });
    if (!teacher || !teacher.phone) {
        return false;
    }

    // 检查phone是否匹配
    return user.phone === teacher.phone;
}

// 权限检查中间件
export const requirePermission = (permissionCode) => {
    return async (req, res, next) => {
        try {
            const userId = req.userId;
            if (!userId) {
                return res.status(401).json({ error: '未认证' });
            }

            const hasAccess = await hasPermission(userId, permissionCode);
            if (!hasAccess) {
                return res.status(403).json({ error: '权限不足' });
            }

            next();
        } catch (error) {
            console.error('权限检查失败:', error);
            return res.status(500).json({ error: '权限检查失败' });
        }
    };
};

// 管理员权限检查中间件
export const requireAdmin = async (req, res, next) => {
    try {
        const userId = req.userId;
        if (!userId) {
            return res.status(401).json({ error: '未认证' });
        }

        if (!(await isAdmin(userId))) {
            return res.status(403).json({ error: '需要管理员权限' });
        }

        next();
    } catch (error) {
        console.error('管理员权限检查失败:', error);
        return res.status(500).json({ error: '权限检查失败' });
    }
};

// 教师管理权限检查（只能管理自己或管理员）
export const canManageTeacherMiddleware = async (req, res, next) => {
    try {
        const userId = req.userId;
        const teacherId = parseInt(req.params.id);

        if (!userId) {
            return res.status(401).json({ error: '未认证' });
        }

        const canManage = await canManageTeacher(userId, teacherId);
        if (!canManage) {
            return res.status(403).json({ error: '只能编辑/删除自己的信息' });
        }

        next();
    } catch (error) {
        console.error('教师管理权限检查失败:', error);
        return res.status(500).json({ error: '权限检查失败' });
    }
};

// 将用户信息附加到请求中
export const attachUserInfo = async (req, res, next) => {
    try {
        const userId = req.userId;
        if (userId) {
            const user = userModel.findOne({ id: userId });
            if (user) {
                req.user = user;
                req.userRoles = await getUserRoles(userId);
                req.isAdmin = req.userRoles.includes(1);
                req.isTeacher = req.userRoles.includes(2);
                req.isStudent = req.userRoles.includes(3);
            }
        }
        next();
    } catch (error) {
        console.error('附加用户信息失败:', error);
        next();
    }
};

